package com.lzj.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzj.admin.pojo.User;
import com.lzj.admin.mapper.UserMapper;
import com.lzj.admin.query.UserQuery;
import com.lzj.admin.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzj.admin.utils.AssertUtil;
import com.lzj.admin.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 王亚栋
 * @since 2022-05-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User findUserByUserName(String userName) {
       return this.baseMapper.selectOne(new QueryWrapper<User>().eq("is_del",0).eq("user_name",userName));

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUserInfo(User user) {

        /**
         * 用户名  非空，唯一
         */
        AssertUtil.isTrue(StringUtil.isEmpty(user.getUsername()),"用户名不能为空！");
        User temp = this.findUserByUserName(user.getUsername());
        AssertUtil.isTrue(null != temp && !(temp.getId().equals(user.getId())),"用户名已存在!");

        AssertUtil.isTrue(!(this.updateById(user)),"用户信息更新失败！");

    }

    /**
     * 修改用户密码
     * @param userName
     * @param oldPassword
     * @param newPassword
     * @param confirmPassword
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUserPassword(String userName, String oldPassword, String newPassword, String confirmPassword) {

        /**
         * 参数校验
         *      用户名  非空唯一，必须存在
         *      原始密码，新密码，确认密码 均不能为空
         *      原始密码必须正确
         *      新密码和确认密码要一致 ，且不能与原始密码相等
         *
         */

        User user = null;
        user = this.findUserByUserName(userName);
        AssertUtil.isTrue(null == user,"用户不存在或未登录！");
        AssertUtil.isTrue(StringUtil.isEmpty(oldPassword),"原密码不能为空!");
        AssertUtil.isTrue(StringUtil.isEmpty(newPassword),"新密码不能为空!");
        AssertUtil.isTrue(StringUtil.isEmpty(confirmPassword),"确认密码不能为空!");
        AssertUtil.isTrue(!(passwordEncoder.matches(oldPassword,user.getPassword())),"原始密码输入错误！");
        AssertUtil.isTrue(!(newPassword.equals(confirmPassword)),"新密码与确认密码不一致，请重新输入！");
        AssertUtil.isTrue(newPassword.equals(oldPassword),"新密码与原始密码不能保持一致!");
        //更新密码
        user.setPassword(passwordEncoder.encode(newPassword));

        AssertUtil.isTrue(!(this.updateById(user)),"密码更新失败！");



    }

    /**
     * 分页
     * @param userQuery
     * @return
     */
    @Override
    public Map<String, Object> userList(UserQuery userQuery) {

        IPage<User> page = new Page<>(userQuery.getPage(),userQuery.getLimit());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",0);
        if (StringUtils.isNotBlank(userQuery.getUserName())){
            queryWrapper.like("user_name",userQuery.getUserName());
        }
        page = baseMapper.selectPage(page, queryWrapper);

        Map<String, Object> map = new HashMap<>();

        map.put("code",0);
        map.put("msg","");
        map.put("data",page.getRecords());
        map.put("count",page.getTotal());

        return map;
    }

    /**
     * 用户记录添加
     * @param user
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void saveUser(User user) {
        /**
         * 参数校验
         *      用户名  非空不可重复
         *      用户密码   默认123456
         */
        AssertUtil.isTrue(StringUtils.isBlank(user.getUsername()),"用户名不能为空！");
        AssertUtil.isTrue( null != findUserByUserName(user.getUsername()),"用户名已存在！");
        //密码加密
        user.setPassword(passwordEncoder.encode("123456"));
        user.setIsDel(0);
        AssertUtil.isTrue(!(this.save(user)),"用户记录添加失败！");


    }

    /**
     * 用户记录更新
     * @param user
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUser(User user) {
/**
 * 参数校验
 *      用户名  非空不可重复
 *
 */
        AssertUtil.isTrue(StringUtils.isBlank(user.getUsername()),"用户名不能为空！");
        //修改时用户不能重名
        User temp = this.findUserByUserName(user.getUsername());
        AssertUtil.isTrue(null != temp && !(temp.getId().equals(user.getId())),"用户名已存在！");
        AssertUtil.isTrue(!(this.updateById(user)),"用户记录更新失败！");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteUser(Integer[] ids) {
        AssertUtil.isTrue(null == ids || ids.length == 0,"请选择待删除的记录id");
        List<User> users = new ArrayList<User>();
        for (Integer id : ids){
            User temp = this.getById(id);
            temp.setIsDel(1);
            users.add(temp);
        }
        AssertUtil.isTrue(!(this.updateBatchById(users)),"用户记录删除失败！");

    }
}
